<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getMenuList,
    checkInvalidMenu,
    updateMenu,
    createMenu,
    searchMenu,
  } from '/@/api/sys/resources';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const { createMessage } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          const records = await searchMenu(rowId.value);
          setFieldsValue({
            ...records,
          });
        }
        const treeData = await getMenuList();
        updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });

          var success;
          if (unref(isUpdate)) {
            values.id = unref(rowId);
            var relationCount = checkInvalidMenu(values);
            relationCount.then((rc) => {
              if (rc > 0) {
                const { createConfirm } = useMessage();
                let msg = '';

                if (values.status === 1) {
                  msg = '启用当前资源将同时启用其所有被停用的上级资源，是否继续？';
                } else {
                  msg = '停用当前资源将同时停用其所有被启用的下级资源，是否继续？';
                }
                createConfirm({
                  iconType: 'warning',
                  title: '警告',
                  content: () => msg,
                  onOk: () => {
                    success = updateMenu(values);
                    //成功之后才能关闭界面
                    success.then(() => {
                      createMessage.success('操作成功');
                      closeDrawer();
                      emit('success');
                    });
                  },
                });
              } else {
                success = updateMenu(values);
                //成功之后才能关闭界面
                success.then(() => {
                  createMessage.success('操作成功');
                  closeDrawer();
                  emit('success');
                });
              }
            });
          } else {
            success = createMenu(values);
            //成功之后才能关闭界面
            success.then(() => {
              createMessage.success('操作成功');
              closeDrawer();
              emit('success');
            });
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
